import { defineComponent, toRefs, reactive, watch, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getAccessToken } from '@/utils/auth'
import WebStorageCache from 'web-storage-cache'
import { CACHE_KEY ,useCache} from '@/hooks/web/useCache'
import { ElNotification } from 'element-plus'


import axios from 'axios'
import qs from 'qs'
import download from '@/utils/download'
import 'amis/sdk/sdk.js'
import 'amis/sdk/rest.js'
import 'amis/sdk/tinymce.js'
import 'amis/sdk/pdf-viewer.js'

import 'amis/sdk/sdk.css'
import 'amis/lib/helper.css'
import 'amis-ui/lib/themes/antd.css'
// import 'amis/sdk/iconfont.css'
// import 'amis/sdk/helper.css'

// import '@fortawesome/fontawesome-free/css/all.css'
// import '@fortawesome/fontawesome-free/js/all'
// import 'amis/lib/themes/default.css'

// import 'amis-ui/lib/themes/cxd.css'
import { service } from "@/config/axios/fecher";

import './index.scss'

const props = {
  schema: {
    type: Object,
    value: () => { },
  },
  env: {
    type: Object,
    default: () => ({}),
  },
}
export default defineComponent({
  props,
  emits: ['ready'],
  setup(props, ctx) {
    const router = useRouter()
    const common = reactive({})
    const { wsCache } = useCache()
    const user = wsCache.get(CACHE_KEY.USER)
    const userInfo = wsCache.get(CACHE_KEY.USERINFO)
    console.log(user)
    const renderBox = ref('renderBox')
    const location = () => {
      const current = router.currentRoute.value
      return {
        pathname: current.path,
        hash: current.hash,
        query: current.query,
        search: `?${qs.stringify(current.query)}`,
      }
    }
    const hanldeNext = () => {
      // window.open('#/editor', '_blank')
    }
    watch(
      () => props.schema,
      () => {
        
      }
    )
    const getList = () => {
      // @ts-ignore
      const scoped = amisRequire('amis/embed')
      // @ts-ignore
      const { normalizeLink } = amisRequire('amis')
      console.log(user)
      const instance = scoped.embed(
        renderBox.value,
        props.schema,
        {
          // 这里是初始 props，一般不用传。
          // locale: 'en-US' // props 中可以设置语言，默认是中文
          // theme: 'ant'
          data: {
            permissions: user.permissions,
            front_user:user,
            user_Info:userInfo
          }
        },
        {
           // 下面三个接口必须实现
           fetcher: service,
          //  fetcher: async ({
          //   url, // 接口地址
          //   method, // 请求方法 get、post、put、delete
          //   data, // 请求数据
          //   responseType,
          //   config, // 其他配置
          //   headers // 请求头
          // }: any) => {
           
          //   config = config || {};
          //   config.withCredentials = true;
          //   responseType && (config.responseType = responseType);

          //   if (config.cancelExecutor) {
          //     config.cancelToken = new (axios as any).CancelToken(
          //       config.cancelExecutor
          //     );
          //   }
          //   if(config.responseType){}
         
          //   config.headers = {...headers,Authorization:'Bearer ' + getAccessToken() } || {};
          //   if(url.includes('export')){
          //     const res = await axios({
          //       url,
          //       method,
          //       data,
          //       responseType:'blob',
          //       headers:{
          //         Authorization:'Bearer ' + getAccessToken() 
          //       }
          //     })
          //     download.excel(res.data, '字典数据.xls')
          //      return {
          //       status:0,
          //       code:200,
          //       msg: '123',
          //       data: res.data || {}, // data不可以为null，否则amis会报错：没有response Data
          //     }
          //   }
          //   if (method !== 'post' && method !== 'put' && method !== 'patch') {
          //     if (data) {
          //       config.params = data;
          //     }
          //     return (axios as any)[method](url, config);
          //   } else if (data && data instanceof FormData) {
          //     config.headers = config.headers || {};
          //     config.headers['Content-Type'] = 'multipart/form-data';
          //   } else if (
          //     data &&
          //     typeof data !== 'string' &&
          //     !(data instanceof Blob) &&
          //     !(data instanceof ArrayBuffer)
          //   ) {
          //     data = JSON.stringify(data);
          //     config.headers = config.headers || {};
          //     config.headers['Content-Type'] = 'application/json';
          //   }
          //   const res = await (axios as any)[method](url, data, config)
          //   if(res.data.code !== 0){
          //     ElNotification.error(res.data.msg)
          //   }else{
          //     ElNotification.success('操作成功')
          //   }
          //   return res
          // },
           isCancel: (value: any) => (service as any).isCancel(value),
          // requestAdaptor(api) {
          //   return {
          //     ...api,
          //     headers: {
          //       Authorization:'Bearer ' + getAccessToken() 
          //     }
          //   };
          // },
          // responseAdaptor(api, payload, query, request, response) {
          //  console.log(api, payload, query, request, response)
          //   return payload;
          // },
          theme: 'cxd',
          // 覆盖 amis env
          // 参考 https://aisuda.bce.baidu.com/amis/zh-CN/docs/start/getting-started#sdk
          ...props.env,
        },
        () => {
          // ctx.emit('ready', {
          //   instance,
          // })
        }
      )
    }
    onMounted(() => {
        getList()
    })
    return {
      ...toRefs(common),
      hanldeNext,
      props,
      renderBox,
    }
  },
  render() {
    const styles =  {
      // padding:'15px'
    }
    return <div ref="renderBox"   id="renderBox" style={styles}></div>
  },
})
